from util.es import query_data
from util.entity import Article


def recall(keywords):
    """
    从知识库中召回相关的应急预案文档
    """
    print(f"🔍 recall开始处理，关键词: {keywords}")
    articles = []
    
    if keywords:
        for keyword in keywords:
            print(f"🔍 查询关键词: {keyword}")
            # 查询Elasticsearch获取相关文档
            results = query_data("law1", [keyword], ["content", "title"], size=10)
            print(f"🔍 关键词 '{keyword}' 查询到 {len(results) if results else 0} 个文档")
            
            if results:
                for result in results:
                    article = Article(
                        name=result.get('title', ''),
                        content=result.get('content', ''),
                        file_id=result.get('file_id', ''),
                        permission_type=result.get('permission_type', 1),
                        permission_set=result.get('permission_set', []),
                        score=result.get('score', 0)
                    )
                    articles.append(article)
    
    print(f"🔍 总共收集到 {len(articles) if articles else 0} 个文档")
    
    # 去重并排序
    unique_articles = {}
    for article in articles:
        if article.name not in unique_articles:
            unique_articles[article.name] = article
        else:
            # 如果已存在，保留分数更高的
            if article.score > unique_articles[article.name].score:
                unique_articles[article.name] = article
    
    final_articles = list(unique_articles.values())
    print(f"✅ recall完成，去重后剩余 {len(final_articles) if final_articles else 0} 个文档")
    
    return final_articles 